/*
 * Copyright (C) 2011 Fabio Hufschmid at bfh.ch
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package ch.bfh.aeneas.core.io.gesture;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.view.MotionEvent;
import android.gesture.GestureOverlayView;
import android.gesture.Gesture;
import android.gesture.GestureLibrary;
import android.util.Log;
import ch.bfh.aeneas.R;
import ch.bfh.aeneas.exchange.intent.AeneasIntent;
import java.util.List;


/**
 * Is responsible to input gestures and save them
 * @author Fabio Hufschmid at bfh.ch
 */
public class CreateGesture extends Activity {
    private static final float LENGTH_THRESHOLD = 120.0f;

    private Gesture mGesture;
    private View mDoneButton;
    private String mItemName;
    private GestureLibrary mStore;
    private List<Gesture> mGestureList=null;
    private final String LOG_TAG = "AeneasCreateGestureActivity";
    private boolean alreadyExist=false;
    private Resources res;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        res=getResources();
        this.setTitle(res.getString(R.string.creategesture_title));
        setContentView(R.layout.create_gesture_aen);
        mDoneButton = findViewById(R.id.done);

        //mItemName=Long.toString(getIntent().getExtras().getLong("ItemName"));
        mItemName=getIntent().getExtras().getString("ItemName");
        
        GestureOverlayView overlay = (GestureOverlayView) findViewById(R.id.gestures_overlay);
        overlay.addOnGestureListener(new GesturesProcessor());
        
        mStore = GestureBuilderContextMenu.getStore();
        checkForSameGestures();
    }

    /**
     * 
     * {@inheritDoc}
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mGesture != null) {
            outState.putParcelable("gesture", mGesture);
        }
    }

    /**
     * 
     * {@inheritDoc}
     */
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        
        mGesture = savedInstanceState.getParcelable("gesture");
        if (mGesture != null) {
            final GestureOverlayView overlay =
                    (GestureOverlayView) findViewById(R.id.gestures_overlay);
            overlay.post(new Runnable() {
                public void run() {
                    overlay.setGesture(mGesture);
                }
            });

            mDoneButton.setEnabled(true);
        }
    }

    /**Add a gesture to the actual gesture libary
     * the mehtode name is linked in the view description xml gestures_overlay
     * 
     * @param v the save button view
     */
    public void addGesture(View v) {
        if (mGesture != null) {
            
            if(this.alreadyExist)
            {
                //Log.i(LOG_TAG,"Remove existing gesture: "+mItemName);
                this.removeGesture(mItemName);
                
                mStore.save();
                mStore.load();
                //Log.i(LOG_TAG,"Should remove existing entry ");
                
            }
            //Log.i(LOG_TAG,"Add gesture: "+mItemName);
            mStore.addGesture(mItemName, mGesture);
            mStore.save();
            speech(res.getString(R.string.creategesture_gesture_saved));
        } 
        finish();
        
    }
    

    /**Cancel a gesture input
     * the mehtode name is linked in the view description xml gestures_overlay
     * 
     * @param v the cancle button view
     */
    public void cancelGesture(View v) {
//        setResult(RESULT_CANCELED);
        speech(res.getString(R.string.creategesture_gesture_discarded));
        finish();
    }
    
    /**Sends a broadcast for e primitve TTS Output
     * 
     * @param inText the text which is to speak
     */
    public void speech(String inText)
    {
        Intent output = new Intent(AeneasIntent.ACTION_OUTPUT);
        output.putExtra("offAISpeech", inText);
        super.sendBroadcast(output);
    }
     
    /**Sends a broadcast for en intelligent TTS Output
     * 
     * @param inText the text which is to speak
     */
     public void speechAiOn(String inText)
    {
        Intent output = new Intent(AeneasIntent.ACTION_OUTPUT);
        output.putExtra("Speech", inText);
        super.sendBroadcast(output);
    }
    
   /**
    * Checks if a gesture is stored with the same name
    * is there already a gesture, give the user a hint
    */
    public void checkForSameGestures()
    {
        mGestureList=mStore.getGestures(mItemName);
        if(mGestureList==null)
        {
            Log.i(LOG_TAG,"No gesture is defined");
        }
        else if(mGestureList.size()>1)
        { 
            Log.i(LOG_TAG,"Size: "+mGestureList.size());
            this.alreadyExist=true;
        }
        else if(mGestureList.size()==1)
        {
            speech(res.getString(R.string.creategesture_already_defined));
            this.alreadyExist=true;
        }
    }
    
    /**
     * 
     * @param inName 
     */
    public void removeGesture(String inName){
        mGestureList=mStore.getGestures(inName);
        if(mGestureList.size()==1)
        {
            Gesture lg = mGestureList.get(0);
            mStore.removeGesture(inName,lg);
           
            Log.i(LOG_TAG,"Gesture to delete: "+mGestureList.get(0).getID());
        }
        else
        {
            Log.i(LOG_TAG,"There are more then one gesture with the same name. Gestures found: "+mGestureList.size());
        }
        
    }
    
    
    /**
     * 
     */
    private class GesturesProcessor implements GestureOverlayView.OnGestureListener {
        public void onGestureStarted(GestureOverlayView overlay, MotionEvent event) {
            mDoneButton.setEnabled(false);
            mGesture = null;
        }

        public void onGesture(GestureOverlayView overlay, MotionEvent event) {
        }

        public void onGestureEnded(GestureOverlayView overlay, MotionEvent event) {
            mGesture = overlay.getGesture();
            if (mGesture.getLength() < LENGTH_THRESHOLD) {
                overlay.clear(false);
            }
            mDoneButton.setEnabled(true);
        }

        public void onGestureCancelled(GestureOverlayView overlay, MotionEvent event) {
        }
    }
}
